package cn.zh.stan.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.TextView;

import com.lzy.okhttputils.OkHttpUtils;
import com.lzy.okhttputils.callback.StringCallback;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;

import cn.zh.stan.BaseUrl;
import cn.zh.stan.ITem.GooodItem;
import cn.zh.stan.ITem.Order;
import cn.zh.stan.R;
import cn.zh.stan.activity.MainActivity;
import cn.zh.stan.activity.OrderDetail;
import cn.zh.stan.adapter.OrderAdapter;
import cn.zh.stan.util.MyListener;
import cn.zh.stan.util.PullToRefreshLayout;
import cn.zh.stan.util.PullableListView;
import okhttp3.Call;
import okhttp3.Request;
import okhttp3.Response;

/**
 * Created by WYN on 2018/2/13 0013.
 */

public class TPGooods extends Fragment implements PullableListView.OnLoadListener{

    PullableListView tplist;
    PullToRefreshLayout tp_layout;
    MainActivity mainAc=null;
    String uid="";

    int page=1;
    OrderAdapter odAdapter=null;
    ArrayList<Order> orders=new ArrayList<Order>();

    TextView tpempty;
    public static final int INIT = 0;
    public static final int STOP = 2;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.tpg_layout,container,false);
        initp(view);
        return view;
        }


    @Override
    public void onResume() {
        super.onResume();
        getOrder("1");
       }


    public void initp(View view){
        mainAc= (MainActivity) getActivity();
        uid=mainAc.getUid();
        tplist=view.findViewById(R.id.tplist);
        tp_layout=view.findViewById(R.id.tp_layout);
        tpempty=view.findViewById(R.id.tpempty);
        tplist.setOnLoadListener(this);
        tp_layout.setOnRefreshListener(new MyListener(){
            @Override
            public void onRefresh(PullToRefreshLayout pullToRefreshLayout) {
                super.onRefresh(pullToRefreshLayout);
                //下拉刷新
                getOrder("1");
             }
          });
        odAdapter=new OrderAdapter(getActivity(),orders,uid);
        tplist.setAdapter(odAdapter);
        tplist.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {

                Intent intent = new Intent();
                intent.setClass(getActivity(), OrderDetail.class);
                intent.putExtra("cd",orders.get(i));
                startActivity(intent);
            }
        });

       }


    @Override
    public void onLoad(PullableListView pullableListView) {
        page=page+1;
        getOrder(page+"");

    }



    public void getOrder(final String page){
        OkHttpUtils.get(BaseUrl.GetOrderPager)
                .params("userId",uid)
                .params("pageIndex",page)
                .params("pageSize","5")
                .params("tradeStatus","0")
                .execute(new StringCallback() {
                    @Override
                    public void onResponse(boolean isFromCache, String s, Request request, @Nullable Response response) {
                        try {
                            JSONObject js=new JSONObject(s);
                            boolean State=js.getBoolean("State");
                            if (State){
                                boolean Flag=js.getBoolean("Flag");
                                if (Flag){
                                    JSONArray Data=js.getJSONArray("Data");
                                    tpempty.setVisibility(View.INVISIBLE);
                                    tp_layout.setVisibility(View.VISIBLE);

                                    if (page.equals("1")){
                                        orders.clear();
                                        if (Data.length()==0){
                                            tpempty.setVisibility(View.VISIBLE);
                                            tp_layout.setVisibility(View.INVISIBLE);
                                            tplist.finishLoading(INIT);
                                            return;
                                        }else {
                                            tpempty.setVisibility(View.INVISIBLE);
                                            tp_layout.setVisibility(View.VISIBLE);
                                        }
                                    }else {
                                        if (Data.length()==0){
                                            tplist.finishLoading(STOP);
                                            return;
                                        }
                                    }


                                    for (int i=0;i<Data.length();i++){
                                        JSONObject ji=Data.getJSONObject(i);
                                        JSONObject Order=ji.getJSONObject("Order");
                                        String Id=Order.getString("Id");
                                        String MemberId=Order.getString("MemberId");
                                        String TradeNo=Order.getString("TradeNo");
                                        String ProvinceName=Order.getString("ProvinceName");
                                        String CityName=Order.getString("CityName");
                                        String CountyName=Order.getString("CountyName");
                                        String CustomerId=Order.getString("CustomerId");
                                        String CustomerName=Order.getString("CustomerName");
                                        String PersonName=Order.getString("PersonName");
                                        String Address=Order.getString("Address");
                                        String Moblie=Order.getString("Moblie");
                                        String CustomeRemark=Order.getString("CustomeRemark");
                                        String LogisticId=Order.getString("LogisticId");
                                        String LogisticName=Order.getString("LogisticName");
                                        String CreateTime=Order.getString("CreateTime");
                                        String PostageTotal=Order.getString("PostageTotal");
                                        String GoodsTotal=Order.getString("GoodsTotal");
                                        String TradeStatus=Order.getString("TradeStatus");
                                        String OrdePayType=Order.getString("OrdePayType");
                                        String OrdePayTime=Order.getString("OrdePayTime");
                                        String SendTime=Order.getString("SendTime");
                                        ArrayList<GooodItem> gooodItems=new ArrayList<GooodItem>();
                                        //获取商品
                                        JSONArray Goods=ji.getJSONArray("Goods");

                                        for (int j=0;j<Goods.length();j++){
                                            JSONObject ja=Goods.getJSONObject(j);
                                            String gId=ja.getString("Id");
                                            String gTradeNo=ja.getString("TradeNo");
                                            String GoodsId=ja.getString("GoodsId");
                                            String SpecId=ja.getString("SpecId");
                                            String GoodsNo=ja.getString("GoodsNo");
                                            int SellCount=ja.getInt("SellCount");
                                            String SellPrice=ja.getString("SellPrice");
                                            String Unit=ja.getString("Unit");
                                            String Image=ja.getString("Image");
                                            GooodItem gooodItem=new GooodItem(gId,gTradeNo,GoodsId,SpecId,GoodsNo,SellCount,SellPrice,Unit,Image);
                                            gooodItems.add(gooodItem);
                                        }

                                        Order order=new Order(Id,MemberId,TradeNo,ProvinceName,CityName,CountyName,CustomerId,CustomerName,
                                                PersonName,Address,Moblie,CustomeRemark,LogisticId,LogisticName,CreateTime,
                                                PostageTotal,GoodsTotal,TradeStatus,OrdePayType,OrdePayTime,SendTime,gooodItems);
                                        orders.add(order);
                                     }
                                    odAdapter.notifyDataSetChanged();
                                    tplist.finishLoading(INIT);
                                }else {
                                    if (page.equals("1")){
                                        tplist.finishLoading(INIT);
                                        if (0==orders.size()){
                                            tpempty.setVisibility(View.VISIBLE);
                                            tp_layout.setVisibility(View.INVISIBLE);
                                        }
                                    }else {
                                        tplist.finishLoading(STOP);
                                    }
                                  }
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                    @Override
                    public void onError(boolean isFromCache, Call call, @Nullable Response response, @Nullable Exception e) {
                        super.onError(isFromCache, call, response, e);
                    }
                });
        }


}
